<?php

namespace App\Models;

class MoneyTransaction extends Model
{
    protected $table = 'money_transactions';

    protected $fillable = [
        'book_id',     // 新增账本ID字段
        'user_id',
        'category_id',
        'sub_category_id',
        'type',        // 交易类型：income收入，expense支出
        'amount',
        'transaction_date',
        'description',
        'text',
        'image',
        'audio',
        'auto_money_transaction_id',
    ];

    protected $casts = [
        'transaction_date' => 'date',
        'amount' => 'decimal:2',
    ];
    const type_map = [
        1 => '收入',
        2 => '支出',
    ];

    /**
     * 获取该交易记录所属的账本
     */
    public function book()
    {
        return $this->belongsTo(MoneyBook::class, 'book_id');
    }

    /**
     * 获取该交易记录所属的用户
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * 获取该交易记录所属的主分类
     */
    public function category()
    {
        return $this->belongsTo(MoneyCategory::class, 'category_id');
    }

    /**
     * 获取该交易记录所属的子分类
     */
    public function subCategory()
    {
        return $this->belongsTo(MoneySubCategory::class, 'sub_category_id');
    }

    /**
     * 获取该交易记录关联的定时记账任务
     */
    public function autoTransaction()
    {
        return $this->belongsTo(AutoMoneyTransaction::class, 'auto_money_transaction_id');
    }

    public static function formatTextByAi($text, $moneyBook)
    {
        $moneyBook->load(['categories.subCategories']);

        $income_category = $expense_category = [];
        $income_category_text = $expense_category_text = [];
        foreach ($moneyBook->categories as $category) {
            foreach ($category['subCategories'] as $item) {
                $key = $category['id'].'-'.$item['id'];
                $value = $value2 = $category['name'].'-'.$item['name'];
                if ($category['description']) $value2 .= '：'.$category['description'];
                if ($category['type'] == MoneyCategory::TYPE_INCOME) {
                    $income_category[$key] = $value;
                    $income_category_text[$key] = $value2;
                } else {
                    $expense_category[$key] = $value;
                    $expense_category_text[$key] = $value2;
                }
            }
        }

        $ai_model = use_ai_models['format_transaction'];
        $date = date('Y-m-d H:i:s');
        $weekdays = ['日', '一', '二', '三', '四', '五', '六'];
        $weekday = $weekdays[date('w')];
        $date .= ' 星期'.$weekday;
        $data = [
            format_field_name('input') => $text,
            format_field_name('income_category') => implode("\n", $income_category_text),
            format_field_name('expense_category') => implode("\n", $expense_category_text),
            format_field_name('date') => $date,
        ];
        $content = strtr(format_transaction, $data);
//        file_put_contents('1.txt', $content);
//        dd();

        $fields = [
            "type", "amount", "category", "date", "description"
        ];
        $check_func = function ($res) use ($fields, $income_category, $expense_category) {
            if ($res && ($res['answer'] ?? '')) {
                $res = format_json($res['answer']);
                if ($res) {
                    if (isset($res['error']) || count(array_intersect($fields, array_keys($res))) == count($fields)) {
                        if (!isset($res['error'])) {
                            $category_key = array_search($res['category'], $res['type'] == 'income' ? $income_category : $expense_category);
                            if (!$category_key) return false;

                            $tmp = explode('-', $category_key);
                            $res['category_id'] = $tmp[0];
                            $res['sub_category_id'] = $tmp[1];

                            return $res;
                        }
                        return $res;
                    }
                }
            }
            return false;
        };
        $res = auto_chat_bat($content, $ai_model, $check_func);
        return $res;
    }

    public static function formatSimpleTextByAi($text, $moneyBook)
    {
        $moneyBook->load(['categories.subCategories']);

        $income_category = $expense_category = [];
        $income_category_input = $expense_category_input = [];
        foreach ($moneyBook->categories as $category) {
            foreach ($category['subCategories'] as $item) {
                $key = $category['id'].'-'.$item['id'];
                $value = $category['name'].'-'.$item['name'];
                if ($category['type'] == MoneyCategory::TYPE_INCOME) {
                    $income_category[$key] = $value;
                    $income_category_input[] = "- **{$value}**: {$item['description']}";
                } else {
                    $expense_category[$key] = $value;
                    $expense_category_input[] = "- **{$value}**: {$item['description']}";
                }
            }
        }

        $ai_model = use_ai_models['format_transaction'];
        $data = [
            format_field_name('input') => $text,
            format_field_name('income_category') => implode("\n", $income_category_input),
            format_field_name('expense_category') => implode("\n", $expense_category_input),
        ];
        $content = strtr(format_transaction_simple, $data);

        $fields = [
            "type", "category", "description"
        ];
        $check_func = function ($res) use ($fields, $income_category, $expense_category) {
            if ($res && ($res['answer'] ?? '')) {
                $res = format_json($res['answer']);
                if ($res) {
                    if (isset($res['error']) || count(array_intersect($fields, array_keys($res))) == count($fields)) {
                        if (!isset($res['error'])) {
                            $res['type'] = $res['type'] == '收入' ? 'income' : 'expense';
                            $category_key = array_search($res['category'], $res['type'] == 'income' ? $income_category : $expense_category);
                            if (!$category_key) return false;

                            $tmp = explode('-', $category_key);
                            $res['category_id'] = $tmp[0];
                            $res['sub_category_id'] = $tmp[1];

                            return $res;
                        }
                        return $res;
                    }
                }
            }
            return false;
        };
        $res = auto_chat_bat($content, $ai_model, $check_func);
        return $res;
    }
}
